﻿using UnityEngine;
using System.Collections;

public class SheepController : MonoBehaviour
{

    bool inField = false;
    Collider currentField;
	private const float maxVelocity = 80;
	private const float walkSpeed = 0.5f;
	private float moveSpeed = 0f;
	Component[] sounds;
	//bool onGround = false;

    // Use this for initialization
    void Start()
    {
        GameManager.count++;
		sounds = GetComponents<AudioSource>();
        Debug.Log(GameManager.count.ToString());
        Physics.gravity = new Vector3(0, -50.0F, 0);
    }

    // Update is called once per frame
    void Update()
    {
        if (inField && !currentField)
        {
            this.rigidbody.drag = 0;
            Debug.Log("EXITED");
            inField = false;
        }
		Vector2 move = new Vector2(moveSpeed, 0);
		transform.Translate(move);
    }

    void OnTriggerEnter(Collider other)
    {
        switch (other.gameObject.tag)
        {
            case "Field":
                Debug.Log("HIT Field");
                inField = true;
                currentField = other;
                this.rigidbody.drag = 10;
                break;
            default:
                Debug.Log("Default");
                break;
        }
    }
	
	void OnCollisionEnter(Collision other)
	{
		Debug.Log ("collided with " + other.collider.gameObject.name);
		switch (other.collider.gameObject.name)
		{
			case "Ground":
				Debug.Log ("HIT Ground");
				if(other.relativeVelocity.magnitude > maxVelocity)
				{
                    killSheep();
				}
				else
				{
					Debug.Log ("landed safely");
					//onGround = true;
					((AudioSource)sounds[0]).Play();
					beginWalk();
				}
				break;
            case "AnimatedChar":
                Debug.Log("HIT PLAYER");
                if (other.relativeVelocity.magnitude > maxVelocity)
                {
                    killSheep();
                }
                else
                {
					GameManager.sheepCollected++;
					Debug.Log("sheep saved");
					((AudioSource)sounds[0]).Play();
					Destroy(this.gameObject);
                }
                break;
            case "Wall":
                Debug.Log("Got Away");
                Destroy(this.gameObject);
                break;
			default:
				break;
		}
	}
	
	void beginWalk()
	{
		GameObject Player = GameObject.Find("AnimatedChar");
		if(Player.transform.position.x > this.transform.position.x)
			moveSpeed = -walkSpeed;
		else
			moveSpeed = walkSpeed;
	}

    void killSheep()
    {
        ++GameManager.sheepDead;
        Instantiate(Resources.Load("SheepExlodedUpdated"), this.transform.localPosition, Quaternion.identity);
        Destroy(this.gameObject);
    }
}
